<template>
  <view
    class="content"
    :style="{
      'padding-top': height + 'px',
    }"
  >
    <view
      :style="{
        width: '100%',
        height: statusBarHeight + 'px',
        background: 'white',
        position: 'fixed',
        top: 0,
        zIndex: 100,
      }"
    >
    </view>
    <!-- 头部 -->
    <view
      class="head"
      :style="{
        top: statusBarHeight + 'px',
      }"
    >
      <view class="head_left">
        <u-icon
          name="arrow-left"
          color="#444444"
          size="24"
          :bold="true"
          @click="toBack"
        ></u-icon>
      </view>
      <view class="text">{{ titleText }}</view>
    </view>
    <!-- 主体 -->
    <u--form
      labelPosition="left"
      labelWidth="200rpx"
      :model="model1"
      ref="uForm"
      class="form_box"
      :style="{ marginTop: statusBarHeight + 'px' }"
    >
      <u-form-item
        :label="title1"
        prop="userInfo.group"
        ref="item1"
        borderBottom
      >
        <view class="picker_fill" @click="show = true">
          {{ model1.userInfo.group }}
          <u-icon
            name="arrow-down-fill"
            style="margin-left: 16rpx"
          ></u-icon>
        </view>
      </u-form-item>
      <u-form-item
        label="成员身份"
        prop="userInfo.identity"
        ref="item2"
        borderBottom
        v-if="from == 'jiazu'"
      >
        <view class="input_view">
          <u--input
            v-model="model1.userInfo.identity"
            border="none"
            :customStyle="{
              'border-radio': '16rpx',
            }"
            placeholder="填输入成员身份"
            inputAlign="right"
          ></u--input>
        </view>
      </u-form-item>
      <u-form-item
        label="记载标题"
        prop="userInfo.title"
        ref="item2"
        borderBottom
      >
        <view class="input_view">
          <u--input
            v-model="model1.userInfo.title"
            border="none"
            :customStyle="{
              'border-radio': '16rpx',
            }"
            placeholder="填输入标题"
            inputAlign="right"
          ></u--input>
        </view>
      </u-form-item>

      <u-form-item
        labelPosition="top"
        label=""
        prop="content"
        ref="item2"
        borderBottom
      >
        <u--textarea
          border="none"
          style="margin-top: 16rpx"
          height="140"
          v-model="model1.userInfo.content"
          placeholder="将TA的故事记录在此..."
          confirmType="return"
          maxlength="-1"
        ></u--textarea>
      </u-form-item>
      <view class="props">
        <view class="props_up">
          <u-upload
            :use-before-read="true"
            :fileList="fileList1"
            @afterRead="afterRead($event, 1)"
            @beforeRead="beforeRead"
            name="1"
            :multiple="true"
            maxCount="9"
            :previewImage="false"
          >
            <view class="up">
              <image
                style="width: 48rpx; height: 48rpx"
                src="@/static/images/icon_cjtl_shangchuantupianhuoshipin.png"
                mode=""
              ></image>
              <view class="up_text"> 上传图片 </view>
            </view>
          </u-upload>
        </view>

        <view class="props_up">
          <u-upload
            :use-before-read="true"
            :fileList="fileList2"
            @afterRead="afterRead($event, 2)"
            @beforeRead="beforeRead"
            name="1"
            :previewImage="false"
            accept="video"
          >
            <view class="up">
              <image
                style="width: 48rpx; height: 48rpx"
                src="@/static/images/icon_cjtl_shangchuantupianhuoshipin.png"
                mode=""
              ></image>
              <view class="up_text"> 上传视频 </view>
            </view>
          </u-upload>
        </view>
        <view class="props_up">
          <view class="up" @click="toAudio">
            <image
              style="width: 48rpx; height: 48rpx"
              src="@/static/images/icon_cjtl_shangchuanyinpin.png"
              mode=""
            ></image>
            <view class="up_text"> 上传音频 </view>
          </view>
        </view>
      </view>

      <!-- 音频 -->
      <view v-if="src" style="margin-top: 40rpx">
        <com-audio
          :src="src"
          @deleteAudio="deleteAudio"
          :showDelBtn="true"
        ></com-audio>
      </view>

      <!-- 上传文件预览区域 -->
      <view class="preview_box">
        <view
          class="preview_box_item"
          v-for="(imgItem, ind) in fileList"
          :key="ind"
        >
          <!-- 展示图 -->
          <image
            :src="imgItem.url"
            class="file_image"
            v-if="imgItem.type == 'image'"
          ></image>
          <!-- 展示视频 -->
          <view v-if="imgItem.type == 'video'" @click="playVideo(imgItem.url)">
            <image :src="imgItem.url_img" class="file_image"></image>
            <view class="video_cover">
              <view class="video_cover_play">
                <image src="@/static/images/icon_dtym_bofang.png"></image>
              </view>
            </view>
          </view>

          <!-- 删除图标 -->
          <view class="del_image_box">
            <image
              src="@/static/images/my/icon_sczp_shanchu.png"
              class="del_image"
              @click.stop="deletePic(ind)"
            ></image>
          </view>
        </view>
      </view>

      <u-form-item label="权限" prop="userInfo.power" ref="item1" borderBottom>
        <view class="picker_fill" @click="show1 = true">
          {{ model1.userInfo.power }}
          <u-icon
            name="arrow-down-fill"
            style="margin-left: 16rpx"
          ></u-icon>
        </view>
      </u-form-item>

      <u-form-item label="等级限制" ref="item2" borderBottom v-if="showGrade">
          <view class="picker_fill" @click="show3 = true">
            {{ model1.userInfo.grade_auth_text }}
            <u-icon name="arrow-down-fill" style="margin-left: 16rpx"></u-icon>
          </view>
        </u-form-item>


      <view class="fill_text">
        <view class=""> 1、视频文件过大时压缩时间较长，请耐心等待 </view>
        <view class=""> 2、若出现黑屏，请清理手机内存 </view>
        <view class="">
          3、建议您调整手机拍摄清晰度选择720p及以下的规格进行拍摄
        </view>
      </view>

      <view :style="{ height: '200rpx' }"></view>

      <view class="btn">
        <view class="box_btn" @click="subFn"> 发布 </view>
      </view>
    </u--form>

    <u-picker
      :show="show"
      :columns="columns"
      keyName="name"
      @close="show = false"
      :closeOnClickOverlay="true"
      @confirm="confirm"
      @cancel="show = false"
    ></u-picker>
    <select-type
      :show="show3"
      :list="gradeList"
      @colse="gradeColse"
      @confirm="gradeConfirm"
      :defaultValue="true"
      title="等级限制"
    ></select-type>
    <u-picker
      :show="show1"
      keyName="name"
      :columns="columns1"
      @close="show1 = false"
      :closeOnClickOverlay="true"
      @confirm="confirm1"
      @cancel="show1 = false"
    ></u-picker>
	<floatingBall></floatingBall>
  </view>
</template>

<script>
import collect from "@/components/collect.vue"; // 收藏、
import progressBar from "@/pages/components/progress_bar.vue"; //录音
import config from "@/config"; // 配置文件
import storage from "@/common/storage.js"; // 缓存封装
import comAudio from "@/pages/components/audio.vue";
import selectType from "@/components/selectType.vue";
export default {
  components: {
    collect,
    progressBar,
    comAudio,
    selectType
  },

  data() {
    return {
      title: "",
      statusBarHeight: 0,
      height: 0,
      titleText: "添加成员",
      title1: "成员划分",
      from: "",
      model1: {
        userInfo: {
          group: "默认", // 成员划分
          title: "", // 标题
          content: "", // 简介
          identity: "", // 成员身份
          power: "所有人", // 权限
          status: 0,
          grade_auth: 0,
          grade_auth_text: "无限制",
        },
      },
      fileList: [],
      fileList1: [],
      fileList2: [],
      show: false,
      show1: false,
      show3: false,
      columns: [],
      columns1: [
        [
          {
            name: "所有人",
            value: "0",
          },
          {
            name: "粉丝",
            value: "1",
          },
          {
            name: "自己",
            value: "2",
          },
        ],
      ],
      file_id: [], // // 图片/视频文件id集合
      pid: 0,
      pageUrl: "",
      user_id: 0,
      src: "", //音频
      audio_id: "",
      showGrade: false,
      gradeList: [], // 等级限制列表
    };
  },
  onLoad(options) {
    this.from = options.from;
    this.user_id = options.user_id;
    this.pageUrl = storage.get("pageUrl", this.pageUrl);
    console.log(this.pageUrl);
    if (this.from == "jiazu") {
      this.titleText = "添加成员";
      this.title1 = "成员划分";
      this.getChengList(); // 记载类型
    } else {
      this.titleText = "开始记载";
      this.title1 = "记载类型";
      this.getJizaiList(); // 记载类型
    }
    this.getUserInfo();
    this.getGradeList();
  },
  created() {
    const statusBarHeight = uni.getSystemInfoSync(); // 获取手机状态栏高度

    this.statusBarHeight = statusBarHeight.statusBarHeight;
    this.$nextTick(() => {
      uni
        .createSelectorQuery()
        .select(".head")
        .boundingClientRect((data) => {
          this.height = data.height;
        })
        .exec();
    });
  },
  methods: {
    // 获取个人信息
    getUserInfo() {
      this.$http
        .userInfo({hideLoading:true})
        .then((res) => {
          // this.continuousList = res.data.list;
          // console.log(this.continuousList, "文心岛续写选项");
          // console.log(res, "个人信息");
          if (res.data.userInfo.is_teacher || res.data.userInfo.is_senators) {
            this.showGrade = true;
          } else {
            this.showGrade = false;
          }
        })
        .catch((error) => {
          uni.$u.toast(error);
        });
    },

    // 获取等级限制列表
    getGradeList() {
      this.$http
        .userLevelList({hideLoading:true})
        .then((res) => {
          // console.log(res, "等级限制列表");
          let arr = JSON.parse(JSON.stringify(res.data.list));
          arr.unshift({
            level_id: 0,
            level_name: "无限制",
          });
          this.gradeList = arr;
        })
        .catch((error) => {
          uni.$u.toast(error);
        });
    },
    toBack() {
      // uni.redirectTo({
      //   url: this.pageUrl,
      // });
      uni.navigateBack({
        delta: 1,
      });
    },
    // 播放视频
    playVideo(url) {
      // console.log(1111111111111);
      uni.navigateTo({
        url: `/components/preview?type=false&vimg=${url}`,
      });
      // e.preventDefault(); // 阻止按钮的默认点击行为
      // console.log("点击事件被阻止");
    },
    // 删除音频
    deleteAudio() {
      console.log("删除啦");
      this.audio_id = "";
      this.src = "";
    },
    // 删除图片
    deletePic(index) {
      // this[`fileList${event.name}`].splice(event.index, 1);
      this.fileList.splice(index, 1);
      this.file_id.splice(index, 1);
      console.log(this.file_id, "id数组");
      console.log(this.fileList, "展示数组");
    },
    // 新增图片/视频之前的操作
    beforeRead() {
      if (this.file_id.length < 9) {
        this.upVideo = true;
      } else {
        this.upVideo = false;
      }
    },
    // 新增图片/视频
    async afterRead(event, index) {
      if (!this.upVideo) {
        return uni.$u.toast("上传数量已达上限");
      }
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file);
      let fileListLen = this[`fileList${event.name}`].length;
      lists.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: "uploading",
          message: "上传中",
        });
      });
      for (let i = 0; i < lists.length; i++) {
        let result;
        if (index == 1) {
          // 图片
          result = await this.uploadFilePromise(lists[i].url);
        } else {
          // 视频
          result = await this.uploadFilePromiseVideo(lists[i].url);
        }

        let item = this[`fileList${event.name}`][fileListLen];
        this[`fileList${event.name}`].splice(
          fileListLen,
          1,
          Object.assign(item, {
            status: "success",
            message: "",
            url: result,
          })
        );
        fileListLen++;
      }
    },
    // 上传图片
    uploadFilePromise(url) {
      let that = this;
      let token = storage.get("token");
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          url: config.uni_app_web_api_url + "/api/upload/image", // 仅为示例，非真实的接口地址
          filePath: url,
          name: "file",
          formData: {
            user: "test",
          },
          header: {
            "Access-Token": token,
          },
          success: (res) => {
            const data = JSON.parse(res.data);
            that.file_id.push(data.data.fileInfo.file_id);
            that.fileList.push({
              url: data.data.fileInfo.external_url,
              type: "image",
            });
            console.log(that.file_id, "id数组");
            console.log(that.fileList, "展示数组");
            resolve(res.data.data);
          },
        });
      });
    },
    // 上传视频
    uploadFilePromiseVideo(url) {
      let that = this;
      let token = storage.get("token");
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          url: config.uni_app_web_api_url + "/api/upload/video", // 仅为示例，非真实的接口地址
          filePath: url,
          name: "file",
          formData: {
            user: "test",
          },
          header: {
            "Access-Token": token,
          },
          success: (res) => {
            const data = JSON.parse(res.data);
            that.file_id.push(data.data.fileInfo.file_id);
            that.fileList.push({
              url: data.data.fileInfo.external_url,
              type: "video",
              url_img: data.data.fileInfo.url_img,
            });
            console.log(data, "res");
            console.log(that.file_id, "id数组");
            console.log(that.fileList, "展示数组");
            resolve(res.data.data);
          },
        });
      });
    },
    // 录制音频
    toAudio() {
      uni.navigateTo({
        url: "/pages/components/recording_audio",
      });
    },
    confirm(e) {
      console.log("eeee", e);
      this.model1.userInfo.group = e.value[0].name;
      this.pid = e.value[0].id;
      this.show = false;
    },
    confirm1(e) {
      console.log("eeee", e);
      this.model1.userInfo.power = e.value[0].name;
      this.model1.userInfo.status = e.value[0].value;
      this.show1 = false;
    },
    gradeColse() {
      this.show3 = false;
    },
    gradeConfirm(e) {
      // console.log(e, "当前选项");
      this.model1.userInfo.grade_auth = e.level_id;
      this.model1.userInfo.grade_auth_text = e.level_name;
      this.show3 = false;
    },
    // 记载类型列表
    getJizaiList() {
      this.$http
        .homeSelect_type({})
        .then((res) => {
          let arr = [];
          arr.push(res.data.list);
          this.columns = arr;
          console.log(this.columns, "记载类型");
          this.model1.userInfo.group = res.data.list[0].name;
          this.pid = res.data.list[0].id;
        })
        .catch((error) => {
          uni.$u.toast(error);
        });
    },

    // 成员划分列表
    getChengList() {
      this.$http
        .homeFamily_all_select({ user_id: this.user_id })
        .then((res) => {
          let arr = [];
          let list = res.data.list;
          list.unshift({
            name: "默认",
            id: 0,
          });
          arr.push(list);
          this.columns = arr;
          console.log(list, "家族选项");
        })
        .catch((error) => {
          uni.$u.toast(error);
        });
    },

    // 提交
    subFn() {
      console.log(this.audio_id, "音频id");
      if (this.from == "jiazu") {
        if (this.model1.userInfo.identity == "") {
          return uni.$u.toast("请输入成员身份");
        }
        if (this.model1.userInfo.title == "") {
          return uni.$u.toast("请输入记载标题");
        }
        if (this.model1.userInfo.content == "") {
          return uni.$u.toast("请输入内容");
        }
        if (this.model1.userInfo.power == "请选择") {
          return uni.$u.toast("请选择权限");
        }
        this.createFamily();
      } else {
        if (this.model1.userInfo.group == "请选择") {
          return uni.$u.toast("请选择记载类型");
        }

        if (this.model1.userInfo.title == "") {
          return uni.$u.toast("请输入记载标题");
        }
        if (this.model1.userInfo.content == "") {
          return uni.$u.toast("请输入内容");
        }
        if (this.model1.userInfo.power == "请选择") {
          return uni.$u.toast("请选择权限");
        }
        this.createHome();
      }
    },

    // 家族创建接口
    createFamily() {
      if (this.audio_id != "") {
        this.file_id.push(this.audio_id);
      }
      console.log(this.file_id, "文件集合id");
      this.$http
        .homeCreateFamily({
          name: this.model1.userInfo.identity,
          content: this.model1.userInfo.content.replace(/\n/g, "<br/>"),
          file_id: this.file_id.join(","),
          pid: this.pid,
          title: this.model1.userInfo.title,
          status: this.model1.userInfo.status,
          grade_auth: this.model1.userInfo.grade_auth,
        })
        .then((res) => {
          uni.$u.toast(res.message);
          setTimeout(() => {
            uni.navigateBack({
              delta: 1,
            });
          }, 1000);
        })
        .catch((error) => {
          uni.$u.toast(error);
        });
    },

    // 家乡创建接口
    createHome() {
      if (this.audio_id != "") {
        this.file_id.push(this.audio_id);
      }
      console.log(this.file_id, "文件集合id");
      this.$http
        .homeCreateHome({
          name: this.model1.userInfo.title,
          content: this.model1.userInfo.content,
          file_id: this.file_id.join(","),
          pid: this.pid,
          status: this.model1.userInfo.status,
          grade_auth: this.model1.userInfo.grade_auth,
        })
        .then((res) => {
          uni.$u.toast(res.message);
          setTimeout(() => {
            uni.navigateBack({
              delta: 1,
            });
          }, 1000);
        })
        .catch((error) => {
          uni.$u.toast(error);
        });
    },
  },
};
</script>

<style scoped lang="scss">
.content {
  // background: #F7F8FA;
  box-sizing: border-box;
}
.head {
  width: 100%;
  padding: 18rpx 30rpx 47rpx;
  position: fixed;
  display: flex;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
  z-index: 99;
  background: #ffffff;
  .head_left {
    position: absolute;
    left: 30rpx;
  }

  .head_right {
    position: absolute;
    right: 30rpx;
    color: #55b877;
    font-size: 30rpx;
  }

  .text {
    font-size: 36rpx;
    font-family: PingFang SC-Bold, PingFang SC;
    font-weight: 400;
    color: #444444;
  }
}
.form_box {
  padding: 0 30rpx;
  box-sizing: border-box;
  .input_view {
    width: 100%;
  }
  .picker_fill {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    // margin-left: 350rpx;
    // color: rgb(192, 196, 204);
  }
  .u-textarea {
    padding: 0;
  }
  .btn {
    width: 100%;
    padding: 0 30rpx;
    box-sizing: border-box;
    position: fixed;
    bottom: 0;
    left: 0;
    margin-bottom: 80rpx;
    .box_btn {
      width: 100%;
      height: 96rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      background: linear-gradient(360deg, #50b674 0%, #aeddbd 100%);
      border-radius: 48rpx;
      font-size: 30rpx;
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      color: #ffffff;
    }
  }
  .introduce {
    background: #f7f8fa;
    padding: 32rpx;
    border-radius: 16rpx;
    margin-top: 56rpx;
    .introduce_title {
      font-size: 32rpx;
      color: #444444;
    }
    .introduce_text {
      font-size: 26rpx;
      color: #888888;
      margin-top: 16rpx;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      overflow: hidden;
      text-overflow: ellipsis;
      -webkit-line-clamp: 3; /* 控制显示的行数 */
    }
  }
  .props {
    width: 100%;
    margin-top: 10rpx;
    border-bottom: 1rpx solid #eee;
    padding-bottom: 32rpx;
    display: flex;
    .props_text {
      font-size: 24rpx;
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      color: #adadad;
    }

    .props_up {
      margin-top: 24rpx;

      .up {
        width: 156rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
      }

      .up_text {
        font-size: 24rpx;
        font-family: PingFang SC, PingFang SC;
        font-weight: 400;
        color: #888888;
        margin-top: 12rpx;
      }
    }
  }

  .preview_box {
    margin-top: 40rpx;
    .preview_box_item {
      width: 222rpx;
      height: 222rpx;
      display: inline-block;
      margin-right: 8rpx;
      margin-bottom: 8rpx;
      position: relative;
      .file_image {
        width: 222rpx;
        height: 222rpx;
        margin-right: 10rpx;
        /deep/.uni-video-cover-duration {
          display: none;
        }
        /deep/ .uni-video-cover {
          display: none;
        }
      }
      .video_cover {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(1, 1, 1, 0.5);
        display: flex;
        align-items: center;
        justify-content: center;
        .video_cover_play {
          width: 80rpx;
          height: 80rpx;
          image {
            width: 80rpx;
            height: 80rpx;
          }
        }
      }
      .del_image_box {
        z-index: 100;
        width: 32rpx;
        height: 32rpx;
        position: absolute;
        right: 0;
        top: 0;
        background: rgba(68, 68, 68, 0.3);
        .del_image {
          width: 32rpx;
          height: 32rpx;
        }
      }
    }
    .preview_box_item:nth-child(3n) {
      margin-right: 0;
    }
  }
  .fill_text {
    width: 100%;
    margin-top: 32rpx;
    font-size: 24rpx;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    color: #888888;
    line-height: 40rpx;
    margin-bottom: 200rpx;
  }
  .none_box {
    height: 100rpx;
  }
}
</style>